package com.navinfo.opentsp.qingqi.trackoptimize.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Http请求工具类
 *
 * @author ZhaiCY
 */
public class HttpUtil {

    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * Http请求
     *
     * @param url   请求URL
     * @param param 请求参数
     * @param token 请求TOKEN
     * @return 请求结果
     */
    public static String get(String url, String param, String token) {
        Map<String, String> headers = new HashMap<String, String>();
        if (!StringUtil.isEmpty(token)) {
            headers.put("token", token);
        }
        return get(url, param, headers);
    }

    /**
     * Http请求
     *
     * @param url     请求URL
     * @param param   请求参数
     * @param headers 请求HEADERS
     * @return 请求结果
     */
    public static String get(String url, String param, Map<String, String> headers) {
        try {
//            logger.debug("get request url : {}, param : {}", url, param);
            URL uri = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setReadTimeout(30000);
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (!StringUtil.isEmpty(param)) {
                OutputStream os = conn.getOutputStream();
                os.write(param.getBytes("UTF-8"));
                os.close();
            }

            conn.connect();

            StringBuilder sb = new StringBuilder();
            int code = conn.getResponseCode();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String msg;
                while ((msg = br.readLine()) != null) {
                    sb.append(msg).append("\n");
                }

                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                }
            } finally {
                if (br != null) {
                    br.close();
                }
            }

            if (code != 200) {
//                logger.error("request url [ " + url + " ] returns code [ " + code + " ]");
            }

//            logger.debug("get request url : {}, response : {}", url, sb.toString());
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Post请求
     *
     * @param url   请求URL
     * @param param 请求参数
     * @param token 请求TOKEN
     * @return 请求结果
     * @throws IOException IOException
     */
    public static String post(String url, String param, String token) throws IOException {
        Map<String, String> headers = new HashMap<String, String>();
        if (!StringUtil.isEmpty(token)) {
            headers.put("token", token);
        }
        return post(url, param, headers);
    }

    /**
     * Post请求
     *
     * @param url     请求URL
     * @param param   请求参数
     * @param headers 请求HEADERS
     * @return 请求结果
     * @throws IOException IOException
     */
    private static String post(String url, String param, Map<String, String> headers) throws IOException {
        logger.debug("post request url : {}, param : {}", url, param);
        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setReadTimeout(30000);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("contentType", "utf-8");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        if (!StringUtil.isEmpty(param)) {
            OutputStream os = conn.getOutputStream();
            os.write(param.getBytes("UTF-8"));
            os.close();
        }

        conn.connect();

        int code = conn.getResponseCode();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String msg;
            while ((msg = br.readLine()) != null) {
                sb.append(msg).append("\n");
            }

            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }

        if (code != 200) {
            logger.error("request url [ " + url + " ] returns code [ " + code + " ]");
            throw new IOException("request url [ "
                    + url + " ] returns code [ " + code + " ], message [ " + sb.toString() + " ]");
        }

        logger.debug("get request url : {}, response : {}", url, sb.toString());
        return sb.toString();
    }
}
